package com.pn.controller;

import com.pn.entity.Place;
import com.pn.entity.Product;
import com.pn.entity.Result;
import com.pn.page.Page;
import com.pn.service.*;
import com.pn.utils.CurrentUser;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@RequestMapping("/product")
@RestController
public class ProductController {
    @Autowired
    private StoreService storeService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private SupplyService supplyService;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private UnitService unitService;
    @Autowired
    private ProductService productService;

    @Autowired
    private TokenUtils tokenUtils;

    @RequestMapping("/store-list")
    public Result storeList() {
        return Result.ok(storeService.queryAllStore());
    }

    /**
     * 查询所有品牌的 url 接口/product/brand-list
     *
     * @return 回值 Result 对象给客户端响应查询到的 List<Brand>;
     */
    @RequestMapping("/brand-list")
    public Result brandList() {
        return Result.ok(brandService.queryAllBrand());
    }

    /**
     * @return 商品分类树
     */
    @RequestMapping("/category-tree")
    public Result categoryTree_() {
        return Result.ok(productTypeService.allProductTypeTree());
    }

    /**
     * @return 所有供应商查询结果
     */
    @RequestMapping("/supply-list")
    public Result supplyList() {
        return Result.ok(supplyService.queryAllSupply());
    }

    /**
     * @return 查询所有产地的结果
     */
    @RequestMapping("/place-list")
    public Result placeList() {
        return Result.ok(placeService.queryAllPlace());
    }

    @RequestMapping("/unit-list")
    public Result unitList() {
        return Result.ok(unitService.queryAllUnit());
    }

    /**
     * @param page    分页实体
     * @param product 商品实体
     * @return 分页查询结果
     */
    @RequestMapping("/product-page-list")
    public Result productPageList(Page page, Product product) {
        return Result.ok(productService.queryProductPage(page, product));
    }

    /**
     * 将配置文件的 file.upload-path 属性值注入给控制器的 uploadPath 属性,
     * 其为图片上传到项目的目录路径(类路径 classes 即 resources 下的
     * static/img/upload);
     */
    @Value("${file.upload-path}")
    private String uploadPath;

    /**
     * @param file 文件路径
     * @return 上传图片的url接口/product/img-upload
     * *
     * * 参数MultipartFile file对象封装了上传的图片;
     * *
     * * @CrossOrigin表示该url接口允许跨域请求;
     */
    @CrossOrigin
    @PostMapping("/img-upload")
    public Result uploadImg(MultipartFile file) {
        try {
            File uploadDirFile = ResourceUtils.getFile(uploadPath);
            String uploadDirPath = uploadDirFile.getAbsolutePath();
            String fileUploadPath = uploadDirPath + "\\" + file.getOriginalFilename();
            file.transferTo(new File(fileUploadPath));
            return Result.ok("图片上传成功");
        } catch (IOException e) {
            return Result.err(Result.CODE_ERR_BUSINESS, "图片上传失败");
        }
    }

    /**
     * 添加商品
     *
     * @param product
     * @param token
     * @return
     */
    @RequestMapping("/product-add")
    public Result addProduct(@RequestBody Product product,
                             @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)
                             String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int createBy = currentUser.getUserId();
        product.setCreateBy(createBy);
        return productService.saveProduct(product);
    }

    /**
     * 修改商品上下架状态的 url 接口/product/state-change
     * *
     * * @RequestBody Product product 用于接收并封装请求 json 数据;
     *
     * @param product
     * @return
     */
    @RequestMapping("/state-change")
    public Result changeProductState(@RequestBody Product product) {
        return productService.updateProductState(product);
    }

    /**
     * 根据商品ID删除商品的业务方法。
     *
     * @param productId 商品ID
     * @return 删除结果
     */
    @RequestMapping("/product-delete/{productId}")
    public Result deleteProduct(@PathVariable Integer productId) {
        return productService.deleteProduct(productId);
    }

    /**
     * 修改商品的 url 接口/product/product-update
     *
     * @ RequestBody Product 将请求传递的 json 数据封装到参数 Product 对象;
     * @ RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头 Token 的值即客户端归还的 token 赋值给参数变量 token;
     */
    @RequestMapping("/product-update")
    public Result updateProduct(@RequestBody Product product,
                                @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String
                                        token) {
//获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
//获取当前登录的用户 id,即修改商品的用户 id
        int updateBy = currentUser.getUserId();
        product.setUpdateBy(updateBy);
//执行业务
        Result result = productService.updateProduct(product);
//响应
        return result;
    }
}
